package splug.cjk;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.*;

import splug.cjk.packet.BBSPacket;


public class BBSFree extends ListActivity implements OnItemClickListener{

	private ArrayList<Content> content;
	private ArrayList<Content> sub_content;
	private ContentAdapter m_adapter;
	private Button btn_write;
	private String id;

	//////////////////////이너클래스 시작
	private class ContentAdapter extends ArrayAdapter<Content> {

		private ArrayList<Content> items;

		public ContentAdapter(Context context, int textViewResourceId, ArrayList<Content> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.list_property, null);
			}
			Content p = items.get(position);
			if (p != null) {
				TextView tt = (TextView) v.findViewById(R.id.toptext);
				TextView bt = (TextView) v.findViewById(R.id.bottomtext);
				if (tt != null){
					tt.setText("제목 : " + p.getTitle());
				}
				if(bt != null){
					bt.setText("글쓴이: "+ p.getId());
				}
			}
			return v;
		}
	}
	
	//////////////////////이너클래스 끝
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("자유 게시판");
		setContentView(R.layout.bbs_free);

		Bundle b = this.getIntent().getExtras();
		id = String.valueOf(b.getString("ID"));

		content = new ArrayList<Content>();
		sub_content = new ArrayList<Content>();

		btn_write = (Button) findViewById(R.id.btn_free_write);
		btn_write.setOnClickListener(on_btn_write);
		
		try {
			Socket socket = new Socket(LetsGoActivity.server_ip, 2007);
			
			InputStream is = socket.getInputStream();
			OutputStream os = socket.getOutputStream();
			
			OutputStreamWriter osw = new OutputStreamWriter(os);
			InputStreamReader isr = new InputStreamReader(is);
			
			osw.write('2');
			osw.flush();
			
			int ack = isr.read();
			
			if(ack == '1'){
				BBSPacket packet = new BBSPacket(content, sub_content,0,"","","","");
				ObjectInputStream input = new ObjectInputStream(is);
				packet = (BBSPacket) input.readObject();
				
				content = packet.getContent();
				sub_content = packet.getSubContent();
			}
			else{
				Toast.makeText(BBSFree.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
				finish();
			}
			
			
		} catch (Exception e) {
			Toast.makeText(BBSFree.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
			finish();
		} 
		
		m_adapter = new ContentAdapter(BBSFree.this, R.layout.list_property, content);
		setListAdapter(m_adapter);
	}

	private View.OnClickListener on_btn_write = new View.OnClickListener() {		
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(BBSFree.this, BBSWrite.class);
			startActivityForResult(intent, 1);
		}
	};

	@Override
	public void onListItemClick(ListView l, View v, int position, long a) {
		super.onListItemClick(l, v, position, a);
		
		Intent intent = new Intent(BBSFree.this, BBSContent.class);
		Bundle b = new Bundle();
		b.putString("ID", id);
		b.putString("AUTHOR", content.get(position).getId());
		b.putString("CONTENT", sub_content.get(position).getTitle());
		b.putString("TIME", sub_content.get(position).getId());
		intent.putExtras(b);
		startActivity(intent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(resultCode == RESULT_OK){
			if(requestCode == 1){
				String tmp_title = data.getStringExtra("TITLE");
				String tmp_content = data.getStringExtra("CONTENT");
				
				//게시물이 쓰여진 시간을 스트링에 저장한다.
				Calendar myCalendar = Calendar.getInstance();
				String tmp_date = Integer.toString(myCalendar
						.get(Calendar.YEAR));
				tmp_date += "/"
						+ Integer.toString(myCalendar
								.get(Calendar.MONTH) + 1);
				tmp_date += "/"
						+ Integer.toString(myCalendar
								.get(Calendar.DAY_OF_MONTH));
				tmp_date += " "
						+ Integer.toString(myCalendar
								.get(Calendar.HOUR_OF_DAY));
				tmp_date += "시 "
						+ Integer.toString(myCalendar
								.get(Calendar.MINUTE)) + "분";

				try {
					Socket socket = new Socket(LetsGoActivity.server_ip, 2007);
					InputStream is = socket.getInputStream();
					OutputStream os = socket.getOutputStream();
					InputStreamReader isr = new InputStreamReader(is);
					OutputStreamWriter osw = new OutputStreamWriter(os);
					
					osw.write('3');
					osw.flush();
					
					int ack = isr.read();
					
					if(ack == '1'){
						BBSPacket packet = new BBSPacket(null,null,0,id,tmp_title,tmp_content,tmp_date);
						ObjectOutputStream output = new ObjectOutputStream(os);
						output.writeObject(packet);
						
						ack = isr.read();
						
						if(ack == '1'){
							Toast.makeText(BBSFree.this, "글쓰기 완료!", Toast.LENGTH_SHORT).show();
						}
						else{
							Toast.makeText(BBSFree.this, "네트워크 상태가 불안정합니다", Toast.LENGTH_SHORT).show();
						}
						
					}
					else{
						Toast.makeText(BBSFree.this, "네트워크 상태가 불안정합니다", Toast.LENGTH_SHORT).show();
					}
					
					
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				

				try {
					Socket socket = new Socket(LetsGoActivity.server_ip, 2007);
					
					InputStream is = socket.getInputStream();
					OutputStream os = socket.getOutputStream();
					
					OutputStreamWriter osw = new OutputStreamWriter(os);
					InputStreamReader isr = new InputStreamReader(is);
					
					osw.write('2');
					osw.flush();
					
					int ack = isr.read();
					
					if(ack == '1'){
						BBSPacket packet = new BBSPacket(content, sub_content,0,"","","","");
						ObjectInputStream input = new ObjectInputStream(is);
						packet = (BBSPacket) input.readObject();
						
						content = packet.getContent();
						sub_content = packet.getSubContent();
					}
					else{
						Toast.makeText(BBSFree.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
					}
					
					
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				
				m_adapter = new ContentAdapter(this, R.layout.list_property, content);
				setListAdapter(m_adapter);
				m_adapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}
	
	
}